<?php
/**
 *
 * User: 罗艳忠
 * Email:luozong05@126.com
 * DateTime: 2017/5/4 14:51
 */

namespace App\Libraries;


class EasyClass
{

// +环境操作相关函数
    /**
     * 函数：get_server_name()
     * 功能：获取当前主域名
     */
    function get_server_name()
    {
        return !empty($_SERVER['HTTP_HOST']) ? strtolower($_SERVER['HTTP_HOST']) : (!empty($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : getenv('SERVER_NAME'));
    }


// +Curl操作相关函数
    /**
     * 函数：ccurl_post($curlpost='',$url='') $curlpost要Post的数据 $url Post目标地址
     * 功能：通过Curl Post数据
     */
    function ccurl_post($curlpost, $url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlpost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }

    function http_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data))
            );
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    function http_media_request($url, $data = array())
    {
        $ch = curl_init();

        if (class_exists('CURLFile')) {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
        } else {
            if (defined('CURLOPT_SAFE_UPLOAD')) {
                curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            }
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }


// +数字操作相关函数
    /**
     * get_hash($_int, $max=10) $id整数 $max限定阈值
     * 功能：根据$_int 获取一个不大于$max的整数。此函数用于分表或规划缓存服务器
     */
    function get_hash($_int, $max = 10)
    {
        $hash = sprintf("%u", crc32($_int));
        return intval(fmod($hash, $max));
    }

// +字符串操作相关函数
    /**
     * 函数：sub_string($string, $length, $dot='...') $string要截取的字符串 $length要截取的长度 $dot截取填充字符默认 ...
     * 功能：字符串截取
     */

    function sub_string($string, $length, $dot = '...')
    {
        $length = $length * 2;

        $string = trim($string);
        $strlen = strlen($string);
        if ($strlen <= $length) return $string;
        $string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
        $strcut = '';
        $n = $tn = $noc = 0;
        while ($n < $strlen) {
            $t = ord($string[$n]);
            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                $tn = 1;
                $n++;
                $noc++;
            } elseif (194 <= $t && $t <= 223) {
                $tn = 2;
                $n += 2;
                $noc += 2;
            } elseif (224 <= $t && $t < 239) {
                $tn = 3;
                $n += 3;
                $noc += 2;
            } elseif (240 <= $t && $t <= 247) {
                $tn = 4;
                $n += 4;
                $noc += 2;
            } elseif (248 <= $t && $t <= 251) {
                $tn = 5;
                $n += 5;
                $noc += 2;
            } elseif ($t == 252 || $t == 253) {
                $tn = 6;
                $n += 6;
                $noc += 2;
            } else {
                $n++;
            }
            if ($noc >= $length) break;
        }
        if ($noc > $length) $n -= $tn;
        $strcut = substr($string, 0, $n);
        $strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
        return $strcut . $dot;
    }

    /*
        生成适合URL传输的base64编码
    */
    function urlsafe_b64encode($string)
    {
        $data = base64_encode($string);
        $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
        return $data;
    }

    function urlsafe_b64decode($string)
    {
        $data = str_replace(array('-', '_'), array('+', '/'), $string);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4);
        }
        return base64_decode($data);
    }

// +安全相关函数
    /**
     * 函数：filter_pass($string) $string要过滤的字符串
     * 功能：入库时(MySQL)过滤危险字符
     */

    function filter_pass($string, $disabledattributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'))
    {

        if (is_array($string)) {
            foreach ($string as $key => $val) $string[$key] = filter_pass($val);
        } else {
            $string = trim($string);

            if (PHP_VERSION < '5.5') {
                $string = stripslashes(preg_replace('/\s(' . implode('|', $disabledattributes) . ').*?([\s\>])/', '\\2', preg_replace('/<(.*?)>/ie', "'<'.preg_replace(array('/javascript:[^\"\']*/i', '/(" . implode('|', $disabledattributes) . ")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", $string)));
            } else {
                $string = stripslashes(preg_replace('/(\s*?)(' . implode('|', $disabledattributes) . ')=([^\s>]+)/i', '', $string));
            }
        }

        return $string;
    }

    /**
     * 函数：pw_trim($string) $string要过滤的字符串或数组
     * 功能：对字符串或数组进行trim过滤
     */
    function pw_trim($string)
    {
        if (!is_array($string)) {
            return trim($string);
        }
        foreach ($string as $key => $value) {
            $string[$key] = pw_trim($value);
        }
        return $string;
    }

    /**
     * 函数：pw_strip_tags($string) $string要过滤的字符串或数组
     * 功能：对字符串或数组进行strip_tags过滤
     */
    function pw_strip_tags($string)
    {
        if (!is_array($string)) {
            return strip_tags($string);
        }
        foreach ($string as $key => $value) {
            $string[$key] = pw_strip_tags($value);
        }
        return $string;
    }

    /**
     * 函数：pw_htmlspecialchars($string) $string要过滤的字符串或数组
     * 功能：对字符串或数组进行htmlspecialchars过滤
     */
    function pw_htmlspecialchars($string)
    {
        if (!is_array($string)) {
            return htmlspecialchars($string);
        }
        foreach ($string as $key => $value) {
            $string[$key] = pw_htmlspecialchars($value);
        }
        return $string;
    }

    /**
     * 函数：pw_stripslashes($string) $string要过滤的字符串或数组
     * 功能：对字符串或数组进行stripslashes过滤
     */
    function pw_stripslashes($str)
    {
        if (!is_array($str)) {
            return stripslashes($str);
        }

        foreach ($str as $key => $value) {
            $str[$key] = pw_stripslashes($value);
        }
        return $str;
    }

    /**
     * 函数：pw_addslashes($string) $string要过滤的字符串或数组
     * 功能：对字符串或数组进行addslashes过滤
     */
    function pw_addslashes($str)
    {
        if (!is_array($str)) {
            return addslashes($str);
        }

        foreach ($str as $key => $value) {
            $str[$key] = pw_addslashes($value);
        }
        return $str;
    }

    /**
     * 函数：pw_md5($str) $str要加密的字符串
     * 功能：返回16位md5加密字符串
     */
    function pw_md5($str)
    {
        return substr(md5($str), 8, 16);
    }


    /**
     * 函数：str_callback_w($str='') $str要检测替换的字符串或数组
     * 功能：对字符串或数组进行检查替换，返回只包含a-z 、0-9、 _字符的结果
     */
    function str_callback_w($str = '')
    {
        if (!is_array($str)) {
            return preg_replace('/[^a-z0-9_\-]/i', '', $str);
        }

        foreach ($str as $key => $value) {
            $str[$key] = str_callback_w($value);
        }
        return $str;
    }

    function nr2PHP_EOL($str = '')
    {
        return str_replace('[_N_R]', PHP_EOL, $str);
    }

    function PHP_EOL2nr($str = '')
    {
        return str_replace(PHP_EOL, '[_N_R]', $str);
    }

// +PHP环境检测函数

    /**
     * is_func_disabled($func)  $func 函数名
     * 功能：检测指定函数是否被PHP.ini禁用函数
     */
    function is_func_disabled($func)
    {
        return in_array($func, array_map('trim', explode(',', ini_get('disable_functions'))));
    }


// +图片视频附件处理相关函数

    /**
     * is_image($img='')  $img图片地址
     * 功能：判断文件是不是一个图片
     */
    function is_image($img = '')
    {
        return in_array(strtolower(get_fileext($img)), array('gif', 'jpg', 'jpeg', 'png', 'bmp'));
    }

    /**
     * is_video($video='')  $video视频地址
     * 功能：判断文件是不是一个视频
     */
    function is_video($video = '')
    {
        return in_array(strtolower(get_fileext($video)), array('flv', 'swf', 'mp4'));
    }

    /**
     * is_voice($voice='')  $voice语音地址
     * 功能：判断文件是不是一个语音
     */
    function is_voice($voice = '')
    {
        return in_array(strtolower(get_fileext($voice)), array('mp3', 'wma', 'wav', 'amr'));
    }

    /**
     * is_attachment($attachment='')  $attachment附件地址
     * 功能：判断文件是不是一个附件
     */
    function is_attachment($attachment = '')
    {
        return in_array(strtolower(get_fileext($attachment)), array('rar', 'zip', 'gz'));
    }

    /**
     * is_pem($pem='')  $pem安全证书地址
     * 功能：判断文件是不是一个安全证书
     */
    function is_pem($pem = '')
    {
        return in_array(strtolower(get_fileext($pem)), array('pem'));
    }

    /**
     * imageinfo($img='')  $img图片地址
     * 功能：获取图片信息
     */
    function imageinfo($img = '')
    {
        $info = array();
        $t = basename($img);
        $t = explode('.', $t);
        $info['name'] = $t[0];
        $info['size'] = filesize($img);
        $imageinfo = getimagesize($img);
        $info['width'] = $imageinfo[0];
        $info['height'] = $imageinfo[1];
        $info['width_height'] = $imageinfo[3];
        $info['mime'] = $imageinfo['mime'];
        unset($imageinfo);
        $imageinfo = pathinfo($img);
        $info['path'] = $imageinfo['dirname'] . '/';
        $info['type'] = strtolower($imageinfo['extension']);
        unset($imageinfo, $name);
        return $info;
    }

// +生成随机数

    /**
     * create_rand($len)  $len 随机字符串长度
     * 功能：生成随机数函数
     */
    function create_rand($len = 32)
    {
        $rand = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

        $str = '';
        for ($i = 0; $i < $len; $i++) {
            $str .= $rand{mt_rand(0, 61)};
        }

        return $str;
    }

// +正则验证

    /**
     * is_username($username='')  $username 用户名字符串
     * 功能：验证是否是用户名
     */
    function is_username($username = '')
    {
        $username = trim($username);

        if (!$username) {
            return false;
        }

        return preg_match('/^[\x80-\xff_a-zA-Z0-9]{1,64}$/i', $username);
    }

    /**
     * is_pwd($pwd='')  $pwd 用户密码
     * 功能：验证是否是用户密码
     */
    function is_pwd($pwd = '')
    {
        $pwd = trim($pwd);

        if (!$pwd) {
            return false;
        }

        return !preg_match('/[\x80-\xff]/i', $pwd);
    }

    /**
     * is_email($email='')  $email 邮箱
     * 功能：验证是否是正确邮箱格式
     */
    function is_email($email = '')
    {
        $email = trim($email);

        if (!$email) {
            return false;
        }

        return preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i', $email);
    }


    /**
     * is_telephone($telephone='')  $telephone 手机号
     * 功能：验证是否是手机号
     */
    function is_telephone($telephone = '')
    {
        $telephone = trim($telephone);

        if (!$telephone) {
            return false;
        }

        return preg_match('/^1[34578]{1}\d{9}$/i', $telephone);
    }

    /**
     * is_qq($qq='')  $qq qq号
     * 功能：验证是否是qq
     */
    function is_qq($qq = '')
    {
        $qq = trim($qq);

        if (!$qq) {
            return false;
        }

        return preg_match('/^[0-9]{5,15}$/i', $qq);
    }

    /**
     * is_in_chinese($str='')  $str 字符串
     * 功能：验证是否[含有]中文字符 常用来校验地址等信息
     */
    function is_in_chinese($str = '')
    {
        $str = trim($str);

        if (!$str) {
            return false;
        }

        return preg_match('/[\x80-\xff]+/i', $str);
    }

    /**
     * is_url($url='')  $url 字符串
     * 功能：验证是否是url
     */
    function is_url($url = '')
    {
        $url = trim($url);

        if (!$url) {
            return false;
        }

        return preg_match('/^http:\/\/[A-Za-z0-9]+\.?[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/i', $url);
    }


    /*
        recurse_copy($src,$dst) 复制文件夹 原目录，复制到的目录
    */
    function recurse_copy($src, $dst)
    {
        $dir = opendir($src);
        @mkdir($dst);
        while (false !== ($file = readdir($dir))) {
            if (($file != '.') && ($file != '..')) {
                if (is_dir($src . '/' . $file)) {
                    recurse_copy($src . '/' . $file, $dst . '/' . $file);
                } else {
                    copy($src . '/' . $file, $dst . '/' . $file);
                }
            }
        }
        closedir($dir);
    }

    /**
     * 微信前端提示函数
     * @param $msg
     * @param string $type
     * @param string $url
     */
    function wealert($msg, $type = "success", $url = '')
    {
        $url = $url ? $url : 'javascript:history.back(-1);';

        if ($type == "success") {
            $html = '<!DOCTYPE html>
				<html lang="en">
				<head>
				<meta charset="UTF-8">
				<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
			    <title>操作提示</title>
			    <link rel="stylesheet" href="' . PW_PATH . 'statics/weui/weui.css"/>
			    <link rel="stylesheet" href="' . PW_PATH . 'statics/weui/weui-max.css"/>
			    <link rel="stylesheet" href="' . PW_PATH . 'statics/weui/weui-extend.css"/>
			    <style type="text/css">
			    	.googs{width: 98%; margin: 0 auto; clear: both}
			    	.googs img{width: 100%}

			    	.btn{width: 98%; margin: 0 auto; clear: both; position: fixed; bottom: .1rem; left: 1%}
			    </style>
			    <script type="text/javascript" src="' . PW_PATH . 'statics/jquery/jquery-1.12.2.min.js"></script>
			    <script language="javascript" type="text/javascript">
			        var PW_PATH="' . PW_PATH . '";
			    </script>
			    <script src="' . PW_PATH . 'statics/core.js" language="javascript"></script>
			    <script src="' . PW_PATH . 'statics/weui/zepto.min.js"></script>
				<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
				<script src="' . PW_PATH . 'statics/weui/weui-extend.js"></script>
			</head>

			<body>
			<div class="weui_msg">
			    <div class="weui_icon_area"><i class="weui_icon_success weui_icon_msg"></i></div>
			    <div class="weui_text_area">
			        <h2 class="weui_msg_title">操作成功</h2>
			        <p class="weui_msg_desc">' . $msg . '</p>
			    </div>
			    <div class="weui_opr_area">
			        <p class="weui_btn_area">
			            <a href="' . $url . '" class="weui_btn weui_btn_primary">确定</a>
			        </p>
			    </div>
			</div>
			</body>
			</html>';
        } else {
            $html = '<!DOCTYPE html>
			<html lang="en">
			<head>
			    <meta charset="UTF-8">
			    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
			    <title>操作提示</title>
			    <link rel="stylesheet" href="' . PW_PATH . 'statics/weui/weui.css"/>
			    <link rel="stylesheet" href="' . PW_PATH . 'statics/weui/weui-max.css"/>
			    <link rel="stylesheet" href="' . PW_PATH . 'statics/weui/weui-extend.css"/>
			    <style type="text/css">
			    	.googs{width: 98%; margin: 0 auto; clear: both}
			    	.googs img{width: 100%}

			    	.btn{width: 98%; margin: 0 auto; clear: both; position: fixed; bottom: .1rem; left: 1%}
			    </style>
			    <script type="text/javascript" src="' . PW_PATH . 'statics/jquery/jquery-1.12.2.min.js"></script>
			    <script language="javascript" type="text/javascript">
			        var PW_PATH="' . PW_PATH . '";
			    </script>
			    <script src="' . PW_PATH . 'statics/core.js" language="javascript"></script>
			    <script src="' . PW_PATH . 'statics/weui/zepto.min.js"></script>
				<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
				<script src="' . PW_PATH . 'statics/weui/weui-extend.js"></script>
			</head>

			<body>
			<div class="weui_msg">
			    <div class="weui_icon_area"><i class="weui_icon_msg weui_icon_warn"></i></div>
			    <div class="weui_text_area">
			        <h2 class="weui_msg_title">操作失败</h2>
			        <p class="weui_msg_desc">' . $msg . '</p>
			    </div>
			    <div class="weui_opr_area">
			        <p class="weui_btn_area">
			            <a href="' . $url . '" class="weui_btn weui_btn_warn">确定</a>
			        </p>
			    </div>
			</div>
			</body>
			</html>';
        }

        exit($html);
    }


    /**
     * 判断是是不是手机访问
     * 手机返回true；pc返回false
     * @return bool
     */
    function is_mobile()
    {
        $regex_match = '/(nokia|iphone|ipad|android|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|';
        $regex_match .= 'htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|';
        $regex_match .= 'blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|';
        $regex_match .= 'symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|';
        $regex_match .= 'jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320×320|240×320|176×220';
        $regex_match .= ')/is';
        return isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE']) or preg_match($regex_match, strtolower($_SERVER['HTTP_USER_AGENT']));
    }

}